#include "DashboardDataWidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QDateTime>
#include <QTimer>
#include <QGraphicsDropShadowEffect>
#include <QLabel>
#include <QPushButton>
#include <QScrollArea>
#include <QComboBox>

namespace ModbusPlexLink {

// ============================================================================
// DataPointCard 实现
// ============================================================================

DataPointCard::DataPointCard(const QString& tagName, const DataPoint& point, QWidget *parent)
    : QFrame(parent)
    , m_tagName(tagName)
    , m_dataPoint(point)
{
    setObjectName("dataPointCard");
    setupUi();
    updateData(point);
}

void DataPointCard::setupUi() {
    setFixedSize(180, 140);

    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->setContentsMargins(12, 10, 12, 10);
    layout->setSpacing(6);

    // 标签名
    m_tagLabel = new QLabel(m_tagName, this);
    m_tagLabel->setObjectName("tagLabel");
    m_tagLabel->setWordWrap(true);
    m_tagLabel->setMaximumHeight(32);
    QFont tagFont = m_tagLabel->font();
    tagFont.setPointSize(9);
    tagFont.setBold(true);
    m_tagLabel->setFont(tagFont);
    layout->addWidget(m_tagLabel);

    // 质量指示器
    m_qualityIndicator = new QLabel(this);
    m_qualityIndicator->setFixedSize(8, 8);
    m_qualityIndicator->setStyleSheet("border-radius: 4px;");

    QHBoxLayout* qualityLayout = new QHBoxLayout();
    qualityLayout->addWidget(m_qualityIndicator);
    qualityLayout->addStretch();
    layout->addLayout(qualityLayout);

    layout->addStretch();

    // 数值
    m_valueLabel = new QLabel(this);
    m_valueLabel->setObjectName("valueLabel");
    m_valueLabel->setAlignment(Qt::AlignCenter);
    QFont valueFont = m_valueLabel->font();
    valueFont.setPointSize(16);
    valueFont.setBold(true);
    m_valueLabel->setFont(valueFont);
    layout->addWidget(m_valueLabel);

    // 单位（预留）
    m_unitLabel = new QLabel(this);
    m_unitLabel->setObjectName("unitLabel");
    m_unitLabel->setAlignment(Qt::AlignCenter);
    QFont unitFont = m_unitLabel->font();
    unitFont.setPointSize(8);
    m_unitLabel->setFont(unitFont);
    layout->addWidget(m_unitLabel);

    layout->addStretch();

    // 时间戳
    m_timestampLabel = new QLabel(this);
    m_timestampLabel->setObjectName("timestampLabel");
    m_timestampLabel->setAlignment(Qt::AlignRight);
    QFont timeFont = m_timestampLabel->font();
    timeFont.setPointSize(7);
    m_timestampLabel->setFont(timeFont);
    layout->addWidget(m_timestampLabel);

    // 样式
    setStyleSheet(R"(
        #dataPointCard {
            background-color: white;
            border: 1px solid #E5E7EB;
            border-radius: 8px;
        }
        #dataPointCard:hover {
            border-color: #3B82F6;
        }
        #tagLabel {
            color: #374151;
        }
        #valueLabel {
            color: #111827;
        }
        #unitLabel {
            color: #6B7280;
        }
        #timestampLabel {
            color: #9CA3AF;
        }
    )");

    // 阴影
    QGraphicsDropShadowEffect* shadow = new QGraphicsDropShadowEffect(this);
    shadow->setBlurRadius(6);
    shadow->setXOffset(0);
    shadow->setYOffset(2);
    shadow->setColor(QColor(0, 0, 0, 10));
    setGraphicsEffect(shadow);
}

void DataPointCard::updateData(const DataPoint& point) {
    m_dataPoint = point;

    // 更新数值
    m_valueLabel->setText(formatValue(point.value));

    // 更新质量指示器
    QColor qualityColor = getQualityColor(point.quality);
    m_qualityIndicator->setStyleSheet(QString(
        "background-color: %1; border-radius: 4px;"
    ).arg(qualityColor.name()));

    // 更新时间戳
    if (point.timestamp > 0) {
        QDateTime dt = QDateTime::fromMSecsSinceEpoch(point.timestamp);
        m_timestampLabel->setText(dt.toString("hh:mm:ss"));
    } else {
        m_timestampLabel->setText("--:--:--");
    }
}

QString DataPointCard::formatValue(const QVariant& value) const {
    if (!value.isValid() || value.isNull()) {
        return "--";
    }

    bool ok;
    double num = value.toDouble(&ok);
    if (ok) {
        // 格式化数字
        if (qAbs(num) < 0.01 || qAbs(num) > 10000) {
            return QString::number(num, 'e', 2);
        } else {
            return QString::number(num, 'f', 2);
        }
    }

    return value.toString();
}

QColor DataPointCard::getQualityColor(DataQuality quality) const {
    switch (quality) {
        case DataQuality::Good:
            return QColor("#10B981");  // 绿色
        case DataQuality::Bad:
            return QColor("#EF4444");  // 红色
        case DataQuality::Uncertain:
            return QColor("#F59E0B");  // 橙色
        case DataQuality::NotUpdated:
            return QColor("#9CA3AF");  // 灰色
        default:
            return QColor("#6B7280");
    }
}

// ============================================================================
// DashboardDataWidget 实现
// ============================================================================

DashboardDataWidget::DashboardDataWidget(QWidget *parent)
    : QWidget(parent)
    , m_channel(nullptr)
{
    setupUi();

    // 自动刷新定时器
    m_refreshTimer = new QTimer(this);
    connect(m_refreshTimer, &QTimer::timeout,
            this, &DashboardDataWidget::onAutoRefreshTimeout);
    m_refreshTimer->start(2000);  // 每2秒刷新
}

DashboardDataWidget::~DashboardDataWidget() {
}

void DashboardDataWidget::setupUi() {
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);

    // 滚动区域
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setFrameShape(QFrame::NoFrame);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    // 内容容器
    m_contentWidget = new QWidget();
    m_gridLayout = new QGridLayout(m_contentWidget);
    m_gridLayout->setContentsMargins(16, 16, 16, 16);
    m_gridLayout->setSpacing(12);
    m_gridLayout->setAlignment(Qt::AlignTop | Qt::AlignLeft);

    m_scrollArea->setWidget(m_contentWidget);
    mainLayout->addWidget(m_scrollArea);

    // 空状态标签
    m_emptyLabel = new QLabel(tr("🔍 暂无数据\n\n请选择一个运行中的通道"), this);
    m_emptyLabel->setAlignment(Qt::AlignCenter);
    m_emptyLabel->setStyleSheet(R"(
        QLabel {
            color: #9CA3AF;
            font-size: 14px;
            padding: 40px;
        }
    )");
    m_gridLayout->addWidget(m_emptyLabel, 0, 0, Qt::AlignCenter);

    // 滚动区域样式
    m_scrollArea->setStyleSheet(R"(
        QScrollArea {
            background-color: #F9FAFB;
            border: none;
        }
        QScrollBar:vertical {
            border: none;
            background: #F3F4F6;
            width: 10px;
            margin: 0px;
        }
        QScrollBar::handle:vertical {
            background: #D1D5DB;
            min-height: 20px;
            border-radius: 5px;
        }
        QScrollBar::handle:vertical:hover {
            background: #9CA3AF;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            height: 0px;
        }
        QScrollBar:horizontal {
            border: none;
            background: #F3F4F6;
            height: 10px;
            margin: 0px;
        }
        QScrollBar::handle:horizontal {
            background: #D1D5DB;
            min-width: 20px;
            border-radius: 5px;
        }
        QScrollBar::handle:horizontal:hover {
            background: #9CA3AF;
        }
        QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
            width: 0px;
        }
    )");
}

void DashboardDataWidget::setChannel(Channel* channel) {
    // 断开旧通道
    if (m_channel) {
        disconnect(m_channel->getDataModel(), nullptr, this, nullptr);
    }

    m_channel = channel;
    clear();

    // 连接新通道
    if (m_channel) {
        m_emptyLabel->hide();

        UniversalDataModel* udm = m_channel->getDataModel();
        if (udm) {
            connect(udm, &UniversalDataModel::dataUpdated,
                    this, &DashboardDataWidget::onDataUpdated,
                    Qt::UniqueConnection);
        }

        // 立即刷新显示
        refreshDisplay();
    } else {
        m_emptyLabel->show();
    }
}

void DashboardDataWidget::refreshDisplay() {
    if (!m_channel) return;

    UniversalDataModel* udm = m_channel->getDataModel();
    if (!udm) return;

    // 获取所有数据点
    QHash<QString, DataPoint> allPoints = udm->readAllPoints();

    if (allPoints.isEmpty()) {
        if (m_cards.isEmpty()) {
            m_emptyLabel->setText(tr("⏳ 等待数据采集...\n\n通道正在运行，尚未收到数据"));
            m_emptyLabel->show();
        }
        return;
    }

    m_emptyLabel->hide();

    // 更新或添加卡片
    for (auto it = allPoints.constBegin(); it != allPoints.constEnd(); ++it) {
        addOrUpdateCard(it.key(), it.value());
    }
}

void DashboardDataWidget::clear() {
    // 清除所有卡片
    qDeleteAll(m_cards);
    m_cards.clear();

    m_emptyLabel->setText(tr("🔍 暂无数据\n\n请选择一个运行中的通道"));
    m_emptyLabel->show();
}

void DashboardDataWidget::onDataUpdated(const QString& tagName, const DataPoint& point) {
    addOrUpdateCard(tagName, point);
}

void DashboardDataWidget::onAutoRefreshTimeout() {
    // 定期刷新显示（更新时间戳等）
    for (auto card : m_cards) {
        card->update();
    }
}

void DashboardDataWidget::addOrUpdateCard(const QString& tagName, const DataPoint& point) {
    if (m_cards.contains(tagName)) {
        // 更新现有卡片
        m_cards[tagName]->updateData(point);
    } else {
        // 创建新卡片
        DataPointCard* card = new DataPointCard(tagName, point, m_contentWidget);
        m_cards[tagName] = card;

        // 计算网格位置 (每行4个卡片)
        int index = m_cards.size() - 1;
        int row = index / 4;
        int col = index % 4;
        m_gridLayout->addWidget(card, row, col);

        m_emptyLabel->hide();
    }
}

void DashboardDataWidget::rebuildCards() {
    // 暂时不需要实现，卡片是动态添加的
}

} // namespace ModbusPlexLink
